package com.pfzy.ui.activity.notification

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.Color
import android.os.Bundle
import android.view.*
import android.view.ViewTreeObserver.OnGlobalLayoutListener
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.AppCompatImageView
import androidx.appcompat.widget.AppCompatTextView
import com.google.android.material.snackbar.Snackbar
import com.google.android.material.snackbar.Snackbar.SnackbarLayout
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupAnimation
import com.pfzy.ui.R
import com.pfzy.ui.activity.notification.NotificationUtils.mIsStop
import com.pfzy.ui.databinding.ActivityNotificationBinding

/**
 * https://juejin.cn/post/7278566669282787383
 * https://blog.csdn.net/u012230055/article/details/118225327
 * https://blog.csdn.net/chengzhenjia/article/details/129966334
 */
class NotificationActivity : AppCompatActivity(), View.OnClickListener {
    private lateinit var mBind: ActivityNotificationBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBind = ActivityNotificationBinding.inflate(layoutInflater)
        setContentView(mBind.root)
        initView()
    }

    override fun onPause() {
        super.onPause()
        NotificationControlManager.getInstance()?.dismissDialogWithLifecycle()
    }

    override fun onResume() {
        super.onResume()
        NotificationControlManager.getInstance()?.showDialogNeverVisible()
    }

    private fun initView() {
        createReceiver()

        mBind.actNotificationNormal.setOnClickListener(this)
        mBind.actNotificationHigh.setOnClickListener(this)
        mBind.actNotificationProgress.setOnClickListener(this)
        mBind.actNotificationUpdateProgress.setOnClickListener(this)
        mBind.actNotificationBigText.setOnClickListener(this)
        mBind.actNotificationBigImage.setOnClickListener(this)
        mBind.actNotificationCustom.setOnClickListener(this)
        mBind.actNotificationUpdateCustom.setOnClickListener(this)
        mBind.actNotificationToast.setOnClickListener(this)
        mBind.actNotificationToastSnackbar.setOnClickListener(this)
        mBind.actNotificationToastSnackbar2.setOnClickListener(this)
        mBind.actNotificationCustom2.setOnClickListener(this)
        mBind.actNotificationCustom3.setOnClickListener(this)
        mBind.actNotificationXpopup.setOnClickListener(this)
    }

    override fun onClick(v: View?) {
        when (v) {
            mBind.actNotificationNormal -> {
                NotificationUtils.getInstance().showNormal()
            }
            mBind.actNotificationHigh -> {
                NotificationUtils.getInstance().showHigh()
            }
            mBind.actNotificationProgress -> {
                NotificationUtils.getInstance().showProgress()
            }
            mBind.actNotificationUpdateProgress -> {
                NotificationUtils.getInstance().updateProgress()
            }
            mBind.actNotificationBigText -> {
                NotificationUtils.getInstance().showBigText()
            }
            mBind.actNotificationBigImage -> {
                NotificationUtils.getInstance().showBigImage()
            }
            mBind.actNotificationCustom -> {
                NotificationUtils.getInstance().showCustom()
            }
            mBind.actNotificationUpdateCustom -> {
                NotificationUtils.getInstance().showUpdateCustom()
            }
            mBind.actNotificationToast -> {
                toastNormal()
            }
            mBind.actNotificationToastSnackbar -> {
//                val snackbar = toastSnackbar(this, "11111111111", 3000)
//                snackbar!!.show()
            }
            mBind.actNotificationToastSnackbar2 -> {
//                val snackbar =snackHint(this)
//                snackbar!!.show()
            }
            mBind.actNotificationCustom2 -> {
                NotificationUtils.getInstance().sendNotification("您有一个新消息", "请点击通知或打开查看")
            }
            mBind.actNotificationCustom3 -> {
                //发应用内通知
                NotificationControlManager.getInstance()?.showNotificationDialog(
                        "文件上传完成",
                        "文件上传完成,请点击查看详情",
                        this,
                        object : NotificationControlManager.OnNotificationCallback {
                            override fun onCallback() {
                                Toast.makeText(
                                    this@NotificationActivity,
                                    "被点击了",
                                    Toast.LENGTH_SHORT
                                ).show()
                            }
                        })
            }
            mBind.actNotificationXpopup -> {
                XPopup.Builder(this)
                    .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                    .popupAnimation(PopupAnimation.TranslateFromTop)
                    .hasShadowBg(false) // 去掉半透明背景
                    .animationDuration(1000)
                    .asCustom(NotificationMsgPopup(this))
                    .show()
            }

            //                new NotificationDialog2(context,
//                        "接送机-新订单提醒 2",
//                        "你有一笔新的行程订单，请提前联系乘客沟通用车时间",
//                        R.mipmap.common_airport, new NotificationDialog2.OnNotificationClick() {
//                    @Override
//                    public void onClick() {
//                        Toast.makeText(XUtil.getContext(), "被点击了", Toast.LENGTH_SHORT).show();
//                    }
//                });


//                new NotificationDialog2(context,
//                        "接送机-新订单提醒 2",
//                        "你有一笔新的行程订单，请提前联系乘客沟通用车时间",
//                        R.mipmap.common_airport, new NotificationDialog2.OnNotificationClick() {
//                    @Override
//                    public void onClick() {
//                        Toast.makeText(XUtil.getContext(), "被点击了", Toast.LENGTH_SHORT).show();
//                    }
//                });
//            NotificationDialog3.getInstance(com.maitianshanglv.im.app.im.service.MyMqttService.context)!!
//                .showNotificationDialog(
//                    "接送机-新订单提醒 3",
//                    "你有一笔新的行程订单，请提前联系乘客沟通用车时间",
//                    R.mipmap.common_airport, object : OnNotificationClick() {
//                        fun onClick() {
//                            Toast.makeText(XUtil.getContext(), "被点击了", Toast.LENGTH_SHORT).show()
//                        }
//                    })

//                NotificationDialog5.getInstance(context).showNotificationDialog("接送机-新订单提醒 5",
//                        "你有一笔新的行程订单，请提前联系乘客沟通用车时间",
//                        R.mipmap.common_airport, new NotificationDialog5.OnNotificationClick() {
//                            @Override
//                            public void onClick() {
//                                Toast.makeText(XUtil.getContext(), "被点击了", Toast.LENGTH_SHORT).show();
//
//                                Intent intent = new Intent();
//                                Bundle bundle = new Bundle();
//                                bundle.putString("tripId", mqttBaseMessage.getContent().getTripId());
//                                intent.putExtras(bundle);
//                                intent.setClass(context, AirportOrderDetailsActivity2.class);
//                                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                                context.startActivity(intent);
//

//                            }
//                        });


//                                NotificationDialog4.show(context, "接送机-新订单提醒 4","你有一笔新的行程订单，请提前联系乘客沟通用车时间",R.mipmap.common_airport);
//                NotificationDialog4.getInstance(context).showNotificationDialog("接送机-新订单提醒 5",
//                        "你有一笔新的行程订单，请提前联系乘客沟通用车时间",
//                        R.mipmap.common_airport, new NotificationDialog4.OnNotificationClick() {
//                            @Override
//                            public void onClick() {
//                                Toast.makeText(XUtil.getContext(), "被点击了", Toast.LENGTH_SHORT).show();
//                            }
//                        });

//                NotificationControlManager.getInstance().showNotificationDialog(
//                        "接送机-新订单提醒",
//                        "你有一笔新的行程订单，请提前联系乘客沟通用车时间",
//                        R.mipmap.common_airport,
//                        new NotificationControlManager.OnNotificationCallback() {
//                            @Override
//                            public void onCallback() {
//                                Toast.makeText(XUtil.getContext(), "被点击了", Toast.LENGTH_SHORT).show();
//                            }
//                        }
//                );
        }
    }

    private fun toastNormal() {
        val layoutView: View = LayoutInflater.from(this).inflate(R.layout.toast_top, null)
        // 设置文本的参数 设置加载文本文件的参数，必须通过LayoutView获取。
        val timeView = layoutView.findViewById<TextView>(R.id.tv_assist_toast_time)
        val contentView = layoutView.findViewById<TextView>(R.id.tv_assist_toast_content)
        val titletView = layoutView.findViewById<TextView>(R.id.tv_assist_toast_title)
        timeView.text = "时间"
        titletView.text = "头部提示"
        contentView.text = "消息内容"
        // 获得屏幕的宽度
        val wm: WindowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val width = wm.defaultDisplay.width
        val layoutParams = LinearLayout.LayoutParams(width, ViewGroup.LayoutParams.WRAP_CONTENT)
        // 设置TextView的宽度为 屏幕宽度
        layoutView.layoutParams = layoutParams
        // 获得屏幕的宽度
        // 创建toast对象
        val toast = Toast(this)
        // 把要Toast的布局文件放到toast的对象中
        toast.setView(layoutView)
        toast.duration = Toast.LENGTH_LONG
        toast.setGravity(Gravity.TOP, 0, 0)
        toast.view!!.systemUiVisibility =
            View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN //设置Toast可以布局到系统状态栏的下面
        toast.show()
    }

    /**
     * material 1.8.0 以下报错
     */
    private fun toastSnackbar(
        activity: AppCompatActivity,
        message: String?,
        duration: Int
    ): Snackbar? {
        val rootView = activity.findViewById<ViewGroup>(android.R.id.content)
        val mSnackbar = Snackbar.make(rootView, "Replace with your own action", duration)
        val layout = mSnackbar.view as SnackbarLayout
        layout.setBackgroundColor(Color.TRANSPARENT)
        layout.elevation = 0f
        layout.setPadding(0, 0, 0, 0)
        val textView = layout.findViewById<TextView>(R.id.snackbar_text)
        textView.visibility = View.GONE
        val view = LayoutInflater.from(activity).inflate(R.layout.customer_snackbar_toast, layout)
        val ivIcon: AppCompatImageView = view.findViewById(R.id.iv_snack_icon)
        ivIcon.viewTreeObserver.addOnGlobalLayoutListener(object : OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                ivIcon.viewTreeObserver.removeOnGlobalLayoutListener(this)
                ivIcon.setImageResource(activity.applicationInfo.icon)
            }
        })
        val tvMessage: AppCompatTextView = view.findViewById(R.id.tv_snack_message)
        tvMessage.viewTreeObserver.addOnGlobalLayoutListener(object : OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                tvMessage.text = message
                tvMessage.viewTreeObserver.removeOnGlobalLayoutListener(this)
            }
        })
        val param = view.layoutParams as FrameLayout.LayoutParams
        param.gravity = Gravity.CENTER
        mSnackbar.setBackgroundTint(Color.TRANSPARENT)
        return mSnackbar
    }

    private fun snackHint(activity: AppCompatActivity): Snackbar {
        var rootView = activity.findViewById<ViewGroup>(android.R.id.content)
        var mSnackbar =
            Snackbar.make(rootView, "Replace with your own action", Snackbar.LENGTH_INDEFINITE)
        val layout = mSnackbar.view as Snackbar.SnackbarLayout
        layout.setPadding(0, 0, 0, 0)
        val textView =
            layout.findViewById<View>(com.google.android.material.R.id.snackbar_text) as TextView
        textView.visibility = View.INVISIBLE
        var view = LayoutInflater.from(activity).inflate(R.layout.customer_snackbar_toast2, layout)
        var param = view.layoutParams as FrameLayout.LayoutParams
        param.gravity = Gravity.TOP
        mSnackbar.setBackgroundTint(Color.WHITE)
        return mSnackbar
    }

    private var mReceiver: NotificationReceiver? = null

    companion object {

    }

    /**
     * 创建广播接收器
     */
    private fun createReceiver() {
        val intentFilter = IntentFilter()
        // 添加接收事件监听
        intentFilter.addAction(NotificationUtils.getInstance().mStopAction)
        intentFilter.addAction(NotificationUtils.getInstance().mDoneAction)
        mReceiver = NotificationReceiver()
        // 注册广播
        registerReceiver(mReceiver, intentFilter)
    }

    private class NotificationReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            // 拦截接收事件
            if (intent.action == NotificationUtils.getInstance().mStopAction) {
                // 改变状态
                mIsStop = !mIsStop
                val activity = context as? NotificationActivity
                NotificationUtils.getInstance().updateCustomView()
                if (mIsStop) {
                    activity!!.mBind.actNotificationUpdateCustom.text = "继续"
                } else {
                    activity!!.mBind.actNotificationUpdateCustom.text = "暂停"
                }
            } else if (intent.action == NotificationUtils.getInstance().mDoneAction) {
                Toast.makeText(context, "完成", Toast.LENGTH_SHORT).show()
            }
        }
    }
}